<template>
  <div class="regulatory-page">
    <div class="return" @click="goBack">
      <Icon size="25" color="#000000" name="arrow-left" class="back" />
      <div class="title">
        <p class="text">收货地址</p>
      </div>
    </div>
    <div class="address-container">
      <AddressList
          v-model="chosenAddressId"
          :list="list"
          default-tag-text="默认"
          @add="onAdd"
          @click-item="onAddressSelect"
      />
    </div>
  </div>
</template>

<script>
import { Icon, AddressList } from "vant";
import http from "@/plugins/http";

export default {
  name: "AddressView",
  components: { Icon, AddressList },
  props: {
    fromOrder: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      chosenAddressId: '',
      list: [],
    };
  },
  created() {
    this.fetchAddresses();
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    onAdd() {
      this.$router.push('/NewAddView');
    },
    onEdit(item) {
      const query = {
        id: item.id,
        name: item.name,
        tel: item.tel,
        address: item.address,
        moRen: item.isDefault ? 1 : 0,
      };
      const currentQuery = this.$route.query;
      const isSameQuery = Object.keys(query).every(key => query[key] === currentQuery[key]);

      if (this.$route.path !== '/NewAddView' || !isSameQuery) {
        this.$router.push({
          path: '/NewAddView',
          query: query,
        });
      }
    },
    onAddressSelect(item) {
      if (this.fromOrder) {
        this.$emit('select-address-id', item.id);
      } else {
        this.onEdit(item);
      }
    },
    fetchAddresses() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        http.get(`/address/${storedUser}`)
            .then(response => {
              const addresses = response.data;
              if (addresses) {
                let sortedAddresses = addresses.map(item => ({
                  id: item.addressId.toString(),
                  name: item.name,
                  tel: item.contact,
                  address: `${item.province} ${item.city} ${item.district} ${item.addressLine}`,
                  isDefault: item.moRen === 1
                }));
                sortedAddresses = sortedAddresses.sort((a, b) => b.isDefault - a.isDefault);
                this.list = sortedAddresses;
                if (this.list.length > 0) {
                  this.chosenAddressId = this.list[0].id;
                }
              } else {
                console.error("地址数据为空或获取失败");
              }
            })
            .catch(error => {
              console.error("获取地址信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    }
  }
};
</script>

<style scoped>
.regulatory-page {
  background-color: #F6F7F9;
  height: 100vh;
}

.return {
  background-color: #FAEAEA;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.back {
  position: absolute;
  left: 10px;
  text-decoration: none;
}

.title {
  display: flex;
  align-items: center;
}

.text {
  margin: 0;
  color: #000000;
  font-size: 16px;
}
</style>
